<script setup lang="ts">
import { ref, onMounted, watch, defineProps, defineEmits } from 'vue'
import { useRouter } from 'vue-router'
import { Card, List, Input, Empty, Button, message, Pagination, Modal } from 'ant-design-vue'
import { SearchOutlined, DeleteOutlined, EditOutlined, StarOutlined } from '@ant-design/icons-vue'
import { listMyAppVoByPage, listGoodAppVoByPage, deleteApp } from '@/api/appController'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  type: {
    type: String,
    default: 'my', // 'my' or 'good'
    required: true
  },
  title: {
    type: String,
    default: '我的应用'
  }
})

const emit = defineEmits(['refresh'])

const router = useRouter()
const userStore = useUserStore()
const isAdmin = ref(false)

// 状态变量
const loading = ref(false)
const searchValue = ref('')
const appList = ref<API.AppVO[]>([])
const pagination = ref({
  current: 1,
  pageSize: 8,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['8', '12', '16', '20']
})

// 检查是否管理员
onMounted(() => {
  isAdmin.value = userStore.loginUser.userRole === 'admin'
})

// 加载应用列表数据
const loadData = async () => {
  loading.value = true
  try {
    const apiFunction = props.type === 'my' ? listMyAppVoByPage : listGoodAppVoByPage
    
    console.log(`开始加载${props.type}应用列表，页码：${pagination.value.current}，每页数量：${pagination.value.pageSize}`)
    
    const res = await apiFunction({
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
      appName: searchValue.value || undefined
    })
    
    if (res.data?.code === 0 && res.data?.data) {
      appList.value = res.data.data.records || []
      pagination.value.total = res.data.data.totalRow || 0
      
      console.log(`成功加载${appList.value.length}个应用，总数：${pagination.value.total}`)
      
      // 打印应用ID，便于调试
      if (appList.value.length > 0) {
        console.log('应用ID列表：', appList.value.map(app => ({ id: app.id, name: app.appName })))
      }
    } else {
      console.error('加载应用列表失败', res.data)
      message.error(res.data?.message || '获取应用列表失败')
    }
  } catch (error) {
    console.error('获取应用列表失败', error)
    message.error('获取应用列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  pagination.value.current = page
  pagination.value.pageSize = pageSize
  loadData()
}

// 搜索应用
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 查看应用详情
const viewApp = (app: API.AppVO) => {
  if (!app.id) {
    message.error('应用ID不存在')
    return
  }
  
  // 确保ID是字符串格式，避免大整数精度问题
  const appId = String(app.id)
  console.log('点击查看应用详情', { id: appId, name: app.appName })
  
  router.push({
    path: `/chat/${appId}`,
    query: { appName: app.appName }
  })
}

// 编辑应用
const editApp = (app: API.AppVO) => {
  router.push({
    path: `/app/edit/${app.id}`,
    query: { appName: app.appName }
  })
}

// 确认删除应用
const confirmDelete = (app: API.AppVO) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除应用 "${app.appName}" 吗？此操作不可恢复。`,
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    onOk: () => handleDelete(app.id as string)
  })
}

// 删除应用
const handleDelete = async (appId: string) => {
  try {
    console.log('删除应用ID:', appId, '类型:', typeof appId);
    const res = await deleteApp({ id: appId })
    if (res.data?.code === 0 && res.data?.data) {
      message.success('删除成功')
      loadData()
      emit('refresh')
    } else {
      message.error(res.data?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除应用失败', error)
    message.error('删除应用失败')
  }
}

// 设为精选（仅管理员可见）
const setFeatured = (app: API.AppVO) => {
  // 此功能会在管理页面实现
  router.push({
    path: '/admin/appmanage',
    query: { id: String(app.id) }
  })
}

// 监听类型变化重新加载数据
watch(() => props.type, () => {
  pagination.value.current = 1
  loadData()
}, { immediate: true })

// 监听搜索框回车事件
const handlePressEnter = () => {
  handleSearch()
}
</script>

<template>
  <div class="app-list-view">
    <Card :title="title" :bordered="false" class="app-list-card">
      <template #extra>
        <div class="search-wrapper">
          <Input
            v-model:value="searchValue"
            placeholder="搜索应用"
            allowClear
            @press-enter="handlePressEnter"
          >
            <template #suffix>
              <SearchOutlined @click="handleSearch" />
            </template>
          </Input>
        </div>
      </template>
      
      <div class="app-list-container">
        <List
          :loading="loading"
          :data-source="appList"
          :grid="{ gutter: 16, xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 4 }"
        >
          <template #renderItem="{ item }">
            <List.Item>
              <Card
                hoverable
                class="app-card"
                @click="viewApp(item)"
              >
                <div class="app-card-cover">
                  <img
                    v-if="item.cover"
                    :src="item.cover"
                    :alt="item.appName"
                  />
                  <div v-else class="app-card-cover-placeholder">
                    {{ item.appName?.charAt(0)?.toUpperCase() || 'A' }}
                  </div>
                </div>
                <div class="app-card-content">
                  <div class="app-card-header">
                    <h3 class="app-name">{{ item.appName || '未命名应用' }}</h3>
                    <div class="app-priority" v-if="item.priority && item.priority > 0">
                      <StarOutlined />
                    </div>
                  </div>
                  <p class="app-description">{{ item.initPrompt?.slice(0, 50) || '无描述' }}{{ item.initPrompt && item.initPrompt.length > 50 ? '...' : '' }}</p>
                  <div class="app-meta">
                    <span class="app-time">{{ item.updateTime ? new Date(item.updateTime).toLocaleDateString() : '未知时间' }}</span>
                    <div class="app-actions" @click.stop>
                      <Button
                        type="text"
                        size="small"
                        title="编辑"
                        @click="editApp(item)"
                        v-if="(type === 'my' && userStore.loginUser.id === item.userId) || isAdmin"
                      >
                        <template #icon><EditOutlined /></template>
                      </Button>
                      <Button
                        type="text"
                        size="small"
                        title="删除"
                        danger
                        @click="confirmDelete(item)"
                        v-if="(type === 'my' && userStore.loginUser.id === item.userId) || isAdmin"
                      >
                        <template #icon><DeleteOutlined /></template>
                      </Button>
                    </div>
                  </div>
                </div>
              </Card>
            </List.Item>
          </template>
        </List>
        
        <div v-if="!loading && appList.length === 0" class="empty-container">
          <Empty description="暂无应用">
            <Button type="primary" v-if="type === 'my'" @click="router.push('/')">创建应用</Button>
          </Empty>
        </div>
        
        <div v-if="loading && appList.length === 0" class="loading-container">
          <Empty description="加载中..." />
        </div>
      </div>
      
      <div class="pagination-container" v-if="appList.length > 0">
        <Pagination
          v-model:current="pagination.current"
          v-model:pageSize="pagination.pageSize"
          :total="pagination.total"
          :pageSizeOptions="pagination.pageSizeOptions"
          showSizeChanger
          showQuickJumper
          @change="handlePageChange"
        />
      </div>
    </Card>
  </div>
</template>

<style scoped>
.app-list-view {
  width: 100%;
}

.app-list-card {
  margin-bottom: 24px;
}

.search-wrapper {
  width: 250px;
}

.app-list-container {
  min-height: 200px;
}

.empty-container, .loading-container {
  padding: 40px 0;
  text-align: center;
}

.app-card {
  height: 100%;
  transition: all 0.3s;
}

.app-card:hover {
  transform: translateY(-4px);
}

.app-card-cover {
  height: 150px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 8px 8px 0 0;
}

.app-card-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.app-card-cover-placeholder {
  font-size: 48px;
  font-weight: bold;
  color: #1668dc;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #e6f7ff, #bae7ff);
}

.app-card-content {
  padding: 12px 0 4px;
}

.app-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.app-name {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.app-priority {
  color: #faad14;
}

.app-description {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.app-time {
  white-space: nowrap;
}

.app-actions {
  display: flex;
  gap: 4px;
}

.pagination-container {
  margin-top: 24px;
  text-align: right;
}
</style> 